package com.itany.corejava.code11_io.zuoye;

import java.io.File;
import java.io.FileNotFoundException;

/**
 * @author MissChen
 * @version 1.0
 * @date 2023 年11月27日 9:33
 */
public class Test02 {
    public static void main(String[] args) {
        try {
            remove("d:\\Users\\User\\Desktop\\aaa","d:\\Users\\User\\Desktop\\aaa");
        } catch (FileNotFoundException e) {
            System.out.println(e.getMessage());
        }
    }
    public static void remove(String path,String rootPath) throws FileNotFoundException {
        File file=new File(path);//d:\Users\User\Desktop\aaa\bbb   d:\\Users\\User\\Desktop\\aaa
        if(!file.exists()){
            throw new FileNotFoundException("该文件不存在");
        }
        if(file.isDirectory()){//判断是否是目录
            System.out.println(file.listFiles().length);
            if(file.listFiles().length==0){//判断是否是空目录
                String filePath=file.getAbsolutePath();//获取当前文件的绝对路径  d:\Users\User\Desktop\aaa\bbb     d:\\Users\\User\\Desktop\\aaa
                String parentPath=file.getParentFile().getAbsolutePath();//获取父目录的绝对路径 d:\Users\User\Desktop\aaa   d:\\Users\\User\\Desktop
                file.delete();//bbb删除    aaa删除
                System.out.println("已删除目录:"+filePath);
                if(!filePath.equals(rootPath)){//d:\Users\User\Desktop\aaa\bbb      d:\\Users\\User\\Desktop\\aaa        d:\\Users\\User\\Desktop\\aaa  d:\\Users\\User\\Desktop\\aaa
                    remove(parentPath,rootPath);//remove("d:\Users\User\Desktop\aaa","d:\\Users\\User\\Desktop\\aaa");
                }else{
                    return;
                }

            }else{
                File[] files=file.listFiles();
                for(File f:files){
                    remove(f.getAbsolutePath(),rootPath);//remove("d:\Users\User\Desktop\aaa\bbb"，"d:\\Users\\User\\Desktop\\aaa")
                }
            }

        }


    }
}
